package com.hycloud.cloudstack.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hycloud.cloudstack.common.CloudstackApi;
import com.hycloud.cloudstack.model.Host;
import com.hycloud.cloudstack.model.SvrOffering;
import com.hycloud.cloudstack.repository.HostConfigRepository;
import com.hycloud.cloudstack.service.HostService;
import com.hycloud.cloudstack.service.SvrOfferingService;

@Service
public class HostServiceImpl implements HostService {

	@Autowired
	private CloudstackApi cloudstackApi;
	
	@Autowired
	private HostConfigRepository hostConfigRepository;
	
	@Autowired
	private SvrOfferingService svrOfferingService;
//{"queryasyncjobresultresponse":{"accountid":"3e321ad0-a652-11e6-b687-525400c0722b","userid":"3e322688-a652-11e6-b687-525400c0722b","cmd":"org.apache.cloudstack.api.command.admin.vm.DeployVMCmdByAdmin","jobstatus":0,"jobprocstatus":0,"jobresultcode":0,"jobinstancetype":"VirtualMachine","jobinstanceid":"204fdeb4-4bba-4cda-b1e3-f05da7b55a2c","created":"2016-12-23T09:09:14+0800","jobid":"cdc398ba-9233-4103-8df3-8a28e492f964"}}
	@Override
	public void create(Host host) throws Exception {
		Map<String, String> params = new HashMap<String, String>();
		String command = "deployVirtualMachine";
		params.put("command", command);
		params.put("serviceofferingid", creatSvrofferingIfNotExists(host).getId());
		params.put("templateid", host.getTemplateid());
		params.put("zoneid", "67fbcf58-1f17-4be2-aba5-8a6254987b3d");
		params.put("networkids", host.getNetworkids());
		params.put("hypervisor", "VMware");
//		params.put("diskofferingid", "5400119b-0db8-4f73-8b35-5366ce64c160");
//		params.put("size", "30");
		params.put("displayname", host.getDisplayname());
		String result = cloudstackApi.api(params);
	}

	private static String svrofferingName(Host host){
		return host.getCpunumber()+"-"+ host.getMemory();
	}
	
	private SvrOffering creatSvrofferingIfNotExists(Host host) throws Exception{
		String name = svrofferingName(host);
		SvrOffering svrOffering = svrOfferingService.findByName(name);
		if(svrOffering == null){
			svrOffering = new SvrOffering();
			svrOffering.setCpunumber(host.getCpunumber());
			svrOffering.setMemory(host.getMemory());
			svrOffering.setName(name);
			svrOffering = svrOfferingService.createSvrOffering(svrOffering);
		}
		return svrOffering;
	}
	

}
